<template>
  <CustomDialog :drag-dialog="dialogInfo" style="z-index:1201;">
    <el-form ref="form" :model="form" :rules="rules" :disabled="!form.busPageInfo.editable" size="mini" label-width="160px">
      <el-row :gutter="2">
        <el-col :span="6">
          <el-form-item label="组织机构" prop="busMainData.sysOrgCode">
            <OrgsetTreeSelect v-model="form.busMainData.sysOrgCode" :editable="form.busPageInfo.editable && form.busMainData.funProcess === '10'" :has-priv="true" style="width: 200px" />
          </el-form-item>
          <el-form-item label="业务时间" prop="busMainData.busDate">
            <el-date-picker
              v-model="form.busMainData.busDate"
              placeholder="业务时间"
              type="datetime"
              size="mini"
              clearable
              style="width: 200px"
              class="filter-item" />
          </el-form-item>
          <el-form-item label="合同类型" prop="busMainData.contractType">
            <el-select v-model="form.busMainData.contractType" :style="style" size="mini" filterable placeholder="合同类型">
              <el-option
                v-for="(item) in dicts.contract_type"
                :key="item.id"
                :label="item.dictName"
                :value="item.dictCode"/>
            </el-select>
          </el-form-item>
          <el-form-item label="合同编号" prop="busMainData.contractNo">
            <el-input v-model="form.busMainData.contractNo" />
          </el-form-item>
          <el-form-item label="合同开始时间" prop="busMainData.beginDate">
            <el-date-picker
              v-model="form.busMainData.beginDate"
              placeholder="合同开始时间"
              type="date"
              size="mini"
              clearable
              style="width: 200px"
              class="filter-item" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户" prop="busMainData.otherSysOwnerCpy">
            <CpyOrgSetSelectDialog
              v-model="form.busMainData.busOtherCpyName"
              :editable="form.busPageInfo.editable && form.busMainData.funProcess === '10'"
              :cpy-code="form.busMainData.otherSysOwnerCpy"
              :ori-org-code="form.busMainData.otherSysOrgCode"
              cpy-owner-type="custom"
              @cpySelectCallback="cpySelectCallback"
              @orgSetSelectCallback="orgSetSelectCallback" />
          </el-form-item>
          <el-form-item label="合同名称" prop="busMainData.name">
            <el-input v-model="form.busMainData.name" />
          </el-form-item>
          <el-form-item label="客户签约人" prop="busMainData.customSigner">
            <el-input v-model="form.busMainData.customSigner" />
          </el-form-item>
          <el-form-item label="公司签约人" prop="busMainData.companySigner">
            <el-input v-model="form.busMainData.companySigner" />
          </el-form-item>
          <el-form-item label="合同结束时间" prop="busMainData.endDate">
            <el-date-picker
              v-model="form.busMainData.endDate"
              placeholder="合同结束时间"
              type="date"
              size="mini"
              clearable
              style="width: 200px"
              class="filter-item" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="合同金额" prop="busMainData.amount">
            <el-input-number v-model.number="form.busMainData.amount" :controls="false" :precision="2" style="width: 100%" />
          </el-form-item>
          <el-form-item label="产品总金额" prop="busMainData.productAmount">
            <template slot="label">
              产品总金额<IconHelp display-content="折扣前." />
            </template>
            <el-input-number v-model.number="form.busMainData.productAmount" :disabled="true" :controls="false" :precision="2" style="width: 100%" />
          </el-form-item>
          <el-form-item label="产品总折扣" prop="busMainData.productDisaccount">
            <el-input-number v-model.number="form.busMainData.productDisaccount" :controls="false" :precision="2" :mini="0" :max="100" style="width: 100%" />
          </el-form-item>
          <el-form-item label="负责人" prop="busMainData.chargerName">
            <el-input :disabled="true" v-model="form.busMainData.chargerName" />
          </el-form-item>
          <el-form-item label="附档" prop="attachmentList">
            <FileUpload
              ref="fileUpload"
              :editable="form.busPageInfo.editable"
              :sup_this="sup_this"
              :file-limit="5"
              :is-direct-upload="true"
              list-type="list"
              @fileRemoveSuccess="fileRemoveSuccess"
              @fileUploadSuccess="fileUploadSuccess" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-tabs v-model="activeTab">
      <el-tab-pane name="visitDetailTab" label="回访">
        <visit-index ref="visitIndex" />
      </el-tab-pane>
      <el-tab-pane name="contractDetailTab" label="产品明细">
        <contract-detail ref="contractDetail" :contract-details="form.contractDetails" :editable="form.busPageInfo.editable" @setDetails="setContractDetails"/>
      </el-tab-pane>
      <el-tab-pane name="memberDetailTab" label="团队负责人">
        <member-detail ref="memberDetail" :member-details="form.memberDetails" :editable="form.busPageInfo.editable" @setDetails="setMemberDetails"/>
      </el-tab-pane>
    </el-tabs>
    <div v-if="form.busPageInfo.editable" slot="footer" class="modal-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button v-permission="['SYS_ADMIN','COMMON_ADMIN','CRM_CONTRACT_ALL','CRM_CONTRACT_CHANGE','CRM_CONTRACT_CREATE']" :loading="loading" type="primary" @click="doSave">暂存</el-button>
      <el-button v-permission="['SYS_ADMIN','COMMON_ADMIN','CRM_CONTRACT_ALL','CRM_CONTRACT_SUBMIT']" :loading="loading" type="primary" @click="doSubmit">提交</el-button>
    </div>
  </CustomDialog>
</template>

<script>
import contract from '@/api/crm/Contract'
import CpyOrgSetSelectDialog from '@/views/components/CpyOrgSetSelectDialog'
import OrgsetTreeSelect from '@/views/components/OrgsetTreeSelect'
import ContractDetail from './contractDetail'
import MemberDetail from './memberDetail'
import visitIndex from '@/views/crm/visit/index'

export default {
  components: { CpyOrgSetSelectDialog, OrgsetTreeSelect, ContractDetail, MemberDetail, visitIndex },
  dictTypes: ['contract_type'],
  props: {
    sup_this: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      isAdd: false,
      loading: false,
      style: 'width: 184px',
      activeTab: 'visitDetailTab',
      dialogInfo: {
        name: 'contractMngFormDetailDialog',
        title: '合同管理',
        fullScreen: true,
        width: 100,
        height: 100
      },
      form: {
        contractDetails: [],
        memberDetails: [],
        busMainData: {
          id: '',
          enableFlag: 'Y'
        },
        busPageInfo: {
          editable: false
        }
      },
      rules: {
        'busMainData.name': [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 3, max: 100, message: '长度在 3 到 100 个字符', trigger: 'blur' }
        ],
        'busMainData.busDate': [
          { required: true, message: '请选择业务时间', trigger: 'blur' }
        ],
        'busMainData.sysOrgCode': [
          { required: true, message: '请选择机构', trigger: 'blur' }
        ],
        'busMainData.contractType': [
          { required: true, message: '请选择合同类型', trigger: 'blur' }
        ],
        'busMainData.otherSysOwnerCpy': [
          { required: true, message: '请选择客户', trigger: 'blur' }
        ],
        'busMainData.amount': [
          { required: true, message: '请输入合同金额', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    cancel() {
      this.resetForm()
    },
    initDataOfBefore() {
    },
    displayDialog() {
      const { name } = this.dialogInfo
      this.$nextTick(() => {
        this.$modal.show(name)
      })
    },
    hiddenDialog() {
      const { name } = this.dialogInfo
      this.$nextTick(() => {
        this.$modal.hide(name)
      })
    },
    fileRemoveSuccess(file) {
      this.form.attachmentList = this.form.attachmentList.filter(t => t.filePath !== file.filePath)
    },
    fileUploadSuccess(sysAttachment) {
      this.form.attachmentList.push(sysAttachment)
    },
    getOtherDetailData(mainId, replaceFlag, replaceDetailLotFlag) {
      if (mainId) {
        contract.getContractDetailData(mainId, replaceFlag, replaceDetailLotFlag).then(res => {
          this.form.contractDetails = res.data
        })
        contract.getMemberDetailData(mainId, replaceFlag, replaceDetailLotFlag).then(res => {
          this.form.memberDetails = res.data
        })
      }
      setTimeout(() => {
        this.$refs.fileUpload.setFileList(this.form.attachmentList)
      }, 200)
    },
    addData() {
      this.isAdd = true
      const data = { paramBean: {}}
      contract.toAdd(data).then(res => {
        this.displayDialog()
        this.form = res.data
        this.getOtherDetailData(null, true, true)
      }).catch(err => {
        console.log(err)
      })
    },
    copyData(mainId) {
      this.isAdd = true
      const data = { paramBean: { id: mainId }}
      contract.toCopy(data).then(res => {
        this.displayDialog()
        this.form = res.data
        this.getOtherDetailData(mainId, true, true)
      }).catch(err => {
        console.log(err)
      })
    },
    viewMainData(id) {
      const _this = this
      _this.isAdd = false
      const data = { paramBean: { id: id }}
      contract.viewMainData(data).then(res => {
        _this.displayDialog()
        _this.form = res.data
        _this.getOtherDetailData(id, false, false)
        _this.form.busPageInfo.editable = false
        setTimeout(() => {
          _this.loadDetailTab()
        }, 200)
      })
    },
    doSubmit() {
      this.doSingleSave(true)
    },
    doSave() {
      this.doSingleSave(false)
    },
    doSingleSave(isSubmit) {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.form.formSubmit = isSubmit
          this.loading = true
          if (this.isAdd) {
            this.doAdd()
          } else {
            this.doEdit()
          }
        }
      })
    },
    doAdd() {
      contract.addOrEdit(this.form).then(res => {
        this.loading = false
        if (this.isRedirect) {
          this.$router.push({ path: '/crm/contract' })
        } else {
          this.sup_this.init()
        }
        this.resetForm()
      }).catch(err => {
        this.loading = false
        console.log(err)
      })
    },
    doEdit() {
      contract.addOrEdit(this.form).then(res => {
        this.resetForm()
        this.loading = false
        this.sup_this.init()
      }).catch(err => {
        this.loading = false
        console.log(err)
      })
    },
    resetForm() {
      this.hiddenDialog()
      this.$refs['form'].resetFields()
    },
    changeData(busId) {
      const data = { paramBean: { id: busId }}
      contract.toChange(data).then(res => {
        this.displayDialog()
        this.form = res.data
        this.getOtherDetailData(this.form.busMainData.oldMainId, true, false)
      }).catch(err => {
        console.log(err)
      })
    },
    cpySelectCallback(selectedRow, selectObj) {
      this.form.busMainData.otherSysOwnerCpy = ''
      this.form.busMainData.busOtherCpyName = ''
      if (selectedRow) {
        this.form.busMainData.otherSysOwnerCpy = selectedRow.cpyCode
        this.form.busMainData.busOtherCpyName = selectedRow.cpyLongName
      }
      selectObj.cancel()
    },
    orgSetSelectCallback(orgCode) {
      this.form.busMainData.otherSysOrgCode = orgCode
    },
    setContractDetails(details) {
      this.form.contractDetails = details
      this.form.busMainData.productAmount = this.refreshProductAmount()
    },
    setMemberDetails(details) {
      this.form.memberDetails = details
    },
    refreshProductAmount() {
      let totalMoney = 0
      this.form.contractDetails.forEach(tmprow => {
        totalMoney = totalMoney + (tmprow.money || 0)
      })
      return totalMoney
    },
    loadDetailTab() {
      const _this = this
      _this.$refs['visitIndex'].initLoadDataByCode(_this.form.busMainData)
    }
  }
}
</script>
